package com.example.anpuser.controller.crud;

import com.example.anpapi.entity.po.usermodel.User.User;
import com.example.anpapi.entity.vo.R;
import com.example.anpuser.service.interfaces.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户信息添加
     * @param user
     * @return
     */
    @PostMapping("/save")
    public R<User> save(@RequestBody User user){
        log.info("用户添加的信息为:{}",user);
        //MD5密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.save(user);
        return R.success(user,"用户添加成功");
    }

    /**
     * 根据用户id删除用户信息
     * @param user
     * @return
     */
    @DeleteMapping("/remove")
    public R<String> remove(@RequestBody User user){
        log.info("用户删除的信息为:{}",user);
        if(userService.getById(user.getId())!=null)
        {
            userService.removeById(user.getId());
            return R.success(null,"用户删除成功");
        }
        return R.error("未找到该用户");
    }

    /**
     * 根据用户id查找用户信息
     * @param id
     * @return
     */
    @GetMapping("/get")
    public R<User> get(@RequestParam(value = "id") Long id) {
        log.info("查询用户的id为{}", id);
        User user = userService.getById(id);
        return R.success(user, "查询用户信息成功");
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PostMapping("/update")
    public R<User> update(@RequestBody User user){
        log.info("修改的用户信息为{}",user);
        userService.updateById(user);
        return R.success(user,"修改用户信息成功");
    }


}


